var express = require("express");
var router = express.Router();
var { UserModel } = require("../db/model");
var createTokenCheck = require("../refresh");

/* GET users listing. */
router.get("/", function (req, res, next) {
  res.send("respond with a resource");
});

// 登录接口
router.post("/logins", async (req, res) => {
  const body = req.body;
  const data = await UserModel.find().populate("role");
//   console.log(data, "数据");
  const istrue = data.some(
    (item) => item.phone === body.phone && item.password === body.password
  );
//   console.log(istrue, "是否正确");
  if (istrue) {
    const user = body;
    const token = createTokenCheck.getToken("user", "1d");
    const tokens = createTokenCheck.getToken("rxh", "7d");
    res.send({
      code: 200,
      msg: "登录成功",
      token,
      tokens,
      user,
    });
  } else {
    res.send({
      code: 201,
      msg: "登录失败",
    });
  }
});

// 无感刷新token
router.get("/refresh", async (req, res) => {
  const token = req.query.refreshToken;
  const accessToken = createTokenCheck.getToken("user", "1d");
  const refreshToken = createTokenCheck.getToken("rxh", "7d");
  if (createTokenCheck.verify(token)) {
    res.send({
      code: 200,
      msg: "刷新成功",
      accessToken,
      refreshToken,
    });
  } else {
    res.send({
      code: 201,
      msg: "刷新失败",
    });
  }
});

// 查看token是否过期
router.get("/list", async (req, res) => {
  let authHeader = req.headers.authorization;
  // console.log(req.headers,'有没有');
  if (authHeader) {
    const token = authHeader.split(" ")[1]; // 提取Bearer JWT token
    // console.log(token);
    if (createTokenCheck.verify(token)) {
      res.send({
        code: 200,
        msg: "获取成功",
      });
    } else {
      res.send({
        code: 401,
        msg: "token已过期",
      });
    }
  } else {
    res.send({
      code: 406,
      msg: "无效的刷新令牌",
    });
  }
});


// 查找接口
router.get('/userLogin',async(req,res)=>{
    const phone=req.query.phone
    const data=await UserModel.find()
    const idx = data.findIndex(item => item.phone == phone)
    if (idx != -1) {
      const datas = data[idx]
      res.send({
          code: 200,
          msg: '成功',
          datas
      })
  } else {
      res.send({
          code: 300,
          msg: '找不到手机号'
      })
  }
  })
  


module.exports = router;
